import 'dart:io';

import 'package:archive/archive_io.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_rtk/api/api.dart';
import 'package:flutter_rtk/common/common.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';

final ImagePicker picker = ImagePicker();

class ImagePickerUtils {
  ImagePickerUtils._internal();

  factory ImagePickerUtils() => _instance;
  static final ImagePickerUtils _instance = ImagePickerUtils._internal();

  // 实力化dio，链接超时默认10s超时
  static ImagePicker? _picker;

  static init() {
    _picker = ImagePicker();
  }

  openSelectPicture(BuildContext context, Function success, {required String business, bool isUpload = true}) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(20.r), topRight: Radius.circular(20.r)),
      ),
      builder: (BuildContext context) {
        return SizedBox(
          width: double.infinity,
          height: 300.h + MediaQuery.of(context).padding.bottom,
          child: Column(
            children: [
              buildTakePhotoBtn(context, success, isUpload: isUpload, business: business),
              buildTakePicture(context, success, isUpload: isUpload, business: business),
              Container(height: 10.h, color: Colors.grey[200]),
              SizedBox(
                height: 90.h,
                width: double.infinity,
                child: InkWell(
                  onTap: () => Navigator.pop(context),
                  child: Center(child: Text('取消', style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.normal))),
                ),
              ),
              SizedBox(height: MediaQuery.of(context).padding.bottom),
            ],
          ),
        );
      },
    );
  }

  SizedBox buildTakePicture(BuildContext context, Function success, {required bool isUpload, required String business}) {
    return SizedBox(
      height: 100.h,
      width: double.infinity,
      child: InkWell(
        onTap: () {
          Navigator.pop(context);
          _getImage().then((List<XFile> files) async {
            if (files.isEmpty) {
              success([]);
            } else {
              List results = await uploadMultiFiles(files, isUpload, business);
              if (results.isEmpty) {
                EasyLoading.dismiss();
                showToast("图片上传失败,请稍后再试");
                success([]);
                return;
              }
              if (results.length < files.length) {
                EasyLoading.dismiss();
                showToast("图片部分上传失败,请稍后再试");
              }
              // debugPrint(jsonEncode(results));
              success(results);
            }
          });
        },
        child: Center(child: Text('从手机相册选择', style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.w600))),
      ),
    );
  }

  Container buildTakePhotoBtn(BuildContext context, Function success, {required bool isUpload, required String business}) {
    return Container(
      decoration: const BoxDecoration(border: Border(bottom: BorderSide(width: 1.0, color: Color(0xFFE3E3E3)))),
      height: 100.h,
      width: double.infinity,
      child: InkWell(
        onTap: () {
          Navigator.pop(context);
          _getCameraImage().then((XFile? file) async {
            if (file == null) {
              success([]);
            } else {
              List<XFile> files = [];
              files.add(file);
              List results = await uploadMultiFiles(files, isUpload, business);
              if (results.isEmpty) {
                EasyLoading.dismiss();
                showToast("图片上传失败,请稍后再试");
                success([]);
                return;
              }
              success(results);
            }
          });
        },
        child: Center(child: Text('拍照', style: TextStyle(fontSize: 30.sp, fontWeight: FontWeight.w600))),
      ),
    );
  }

  Future<List<dynamic>> uploadMultiFiles(List<XFile> files, bool isUpload, String business) async {
    EasyLoading.show(status: '图片处理中...');
    List<dynamic> results = [];
    try {
      if (files.isEmpty) {
        return results;
      }
      // feat: 支持离线临时存储，后续上传
      if (isUpload) {
        for (var file in files) {
          var res = await AppApi.uploadFile(path: file.path);
          if (res['code'] == 200) {
            results.add(res['data']['link']);
          }
        }
      } else {
        var directory = await getApplicationDocumentsDirectory();
        for (XFile file in files) {
          // copy file to business
          var destFile = File("${directory.path}/${file.name}");
          // copy
          File(file.path).copySync(destFile.path);
          // 文件写入其他目录
          results.add(destFile.path);
        }
      }
    } catch (e, stack) {
      debugPrintStack(stackTrace: stack, label: "$e");
      EasyLoading.showError('图片处理失败, 请稍后重试');
    }
    return results;
  }

  _getCameraImage() {
    return _picker!.pickImage(source: ImageSource.camera, imageQuality: 30);
  }

  _getImage() {
    return _picker!.pickMultiImage(imageQuality: 30);
  }
}
